<template>
    <div class="box">
        <header class="header">
            <van-nav-bar title="购物车" left-arrow @click-left="$router.back()" />
        </header>
        <div class="content">
            <!-- {{ cartList }} -->
            <van-empty v-if="cartList.length == 0" description="购物车是空的" />
            <van-swipe-cell v-else v-for=" item in cartList" :key="item.id">
                <van-card :num="item.count" :price="item.price + '.00'" :title="item.title" :thumb="item.image">
                    <template #tag>
                        <van-checkbox v-model="item.checked"></van-checkbox>
                    </template>
                    <template #footer>
                        <van-stepper v-model="item.count" />
                    </template>
                </van-card>
                <template #right>
                    <van-button square text="删除" type="danger" class="delete-button" @click="onDelete(item.id)" />
                </template>
            </van-swipe-cell>
        </div>
    </div>
    <footer class="footer">
        <van-submit-bar :price="totalPrice" button-text="去结算" @submit="$router.push('/order')">
            <van-checkbox v-model="allChecked">全选</van-checkbox>
        </van-submit-bar>
    </footer>
</template>
<script>
import { useCounterStore } from '@/store/index.js'
import { mapState, mapActions } from 'pinia'
export default {
    computed: {
        ...mapState(useCounterStore, ['cartList', 'totalPrice']),
        allChecked: {
            // 正向： 当列表中所有数据被选中时，全选按钮自动被勾上
            // 反向： 当全选按钮被选中时，列表中所有数据应该自动被勾上
            get() {
                // 获取全选按钮的值
                if (this.cartList.length == 0) {
                    return false
                } else {
                    return this.cartList.every(item => item.checked == true)
                }
            },
            set(val) {
                // 通过全选按钮的val值给列表数据设定
                this.cartList.forEach(item => item.checked = val)
            }
        }
    },
    methods: {
        ...mapActions(useCounterStore, ['deleteItem']),
        onDelete(id) {
            // 触发pinia中deleteItem方法
            this.deleteItem(id)
        }
    }
}
</script>
<style lang="scss" scoped>
.delete-button {
    height: 100%;
}
</style>